# -*- coding: utf8 -*-

import urllib2, feedparser
from puppy.model import Query, Response, Item
from puppy.service.Config import *

def search(query):
  """Search function for Arxiv search.
  
  Parameters:
  
  * query (puppy.model.OpenSearch.Query)
  
  Returns:
  
  * puppy.model.OpenSearch.Response
  
  Raises:
  
  * urllib2.URLError, feedparser error
  
  """
  
  def parse_arxiv_atom(site, query, results):
    """Create a OpenSearch Response from ArXiv's Atom feed.
    
    Arxiv's search API returns results in Atom 1.0. 
	This function parses the atom feed and converts it to an opensearch api reference
    Parameters:
    
    * site (str): search engine name
    * query (str): query search terms (n.b. not a OpenSearch Query object)
    * results (dict): results from service
    
    Returns:
    
    * OpenSearch.Response
    
    """
    response = Response()
    response.title = "{0}: {1}".format(site, query)
    response.link = results['feed']['links'][0]['href']
    response.description = "Search results for '{0}' at {1}".format(query, site)
    #response.total_results = int(results['feed']['opensearch_totalresults'])
    #response.start_index = int(results['feed']['opensearch_startindex'])
    #response.items_per_page = int(results['feed']['opensearch_itemsperpage'])
    response.query = query
    for result in results['entries']:
      item = Item()
      item.title = result['title']
      item.link = result['link']
      item.description = result['summary']
      response.items.append(item)
    return response
  
   
  pos = 1
  url = "http://export.arxiv.org/api/query?search_query=all:{0}&amp;id_list=&amp;start=0&amp;max_results=10".format(urllib2.quote(query.search_terms))
  results = ''
  try:
    response = urllib2.urlopen(url)
    results = feedparser.parse(response)
    #results['ysearchresponse'].setdefault(u'link', url)
    return parse_arxiv_atom('Arxiv Search', query.search_terms, results)
  except urllib2.URLError, e:
    print "Error in SearchService: Arxiv search failed", e
